/**
 * Created with Vim7.3 Mac
 * @fileOverview : 
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-07-06 17:59:33
 * @filename : gesture.js
 * @version : 
 * @description : 
 */


class Gesture {
  
    constructor(options) {
        return this.gesture(options);
    }
  
    gesture(options) {
      
        let opts = {
            priority : ()=>false,
            responder : ()=>true,
            swipeStart : ()=>{}, 
            swipeEnd : ()=>{},
            swipeMove : ()=>{},
            swipeLeft : ()=>{},
            swipeRight : ()=>{},
            swipeUp : ()=>{},
            swipeDown : ()=>{},
        };

        opts = Object.assign({}, opts, options || {});

        let bindEvtObj = {},touch = {};

        if (opts.priority) {
            bindEvtObj.onStartShouldSetResponderCapture= opts.responder;
            bindEvtObj.onMoveShouldSetResponderCapture= opts.responder;
        } else {
            bindEvtObj.onStartShouldSetResponder= opts.responder;
            bindEvtObj.onMoveShouldSetResponder= opts.responder;
        }

        bindEvtObj.onResponderGrant= (e)=> {
            //console.log('start');
            touch.timeStart = e.nativeEvent.timestamp;
            touch.x1 = e.nativeEvent.pageX;
            touch.y1 = e.nativeEvent.pageY;
            touch.x2 = e.nativeEvent.pageX;
            touch.y2 = e.nativeEvent.pageY;
            touch.bool = true;
            opts.swipeStart(touch);
        };

        bindEvtObj.onResponderMove= (e)=> {
            //console.log('move',e.nativeEvent);
            if (touch.bool) {
                touch.x2 = e.nativeEvent.pageX;
                touch.y2 = e.nativeEvent.pageY;
                opts.swipeMove(touch);
            }

        };

        bindEvtObj.onResponderRelease= (e)=> {
            //console.log('end',touch.bool);
            if (touch.bool) {
                touch.bool = false;
                touch.timeEnd = e.nativeEvent.timestamp;
                touch.x2 = e.nativeEvent.pageX;
                touch.y2 = e.nativeEvent.pageY;
                touch.Direction = swipeDirection(touch.x1,touch.x2,touch.y1,touch.y2);
                
                if ((Math.abs(touch.x1 - touch.x2) > 30 || Math.abs(touch.y1 - touch.y2) > 30) && touch.timeEnd - touch.timeStart < 200) {
                    opts['swipe'+touch.Direction](touch);
                } else {
                    opts.swipeEnd(touch);
                }
            }
        }; 

        function swipeDirection (x1, x2, y1, y2) {
            return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
        }

        return bindEvtObj;
    };
}

export default Gesture;
